package com.synchrona.dataProcessor;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Map.Entry;

import javax.xml.stream.XMLStreamException;

import org.apache.commons.httpclient.HttpException;

import com.synchrona.common.TinyURLUtils;
import com.synchrona.update.Update;

public class DataProcessor {
	
	private Update update = null;
	
	public DataProcessor(Update update){
		this.update = update;
	}
	
	public DataProcessor(){
		
	}
	
	//Processes data
	public void processData(){
		Task task = new Task();
		DMMLParser parser = new DMMLParser();
		try {
			task = parser.parseXML(update.getData());
			System.out.println("Site: " + task.getSiteName()+" URL: " + task.getSiteURL());
			HashMap map = (HashMap)task.getHashMap();
			Set set = map.entrySet();
			Iterator iterator = set.iterator();
			while (iterator.hasNext()) {
				Entry entry = (Entry)iterator.next();
				System.out.println(entry.getKey() + " : " + entry.getValue());
				
			}
		} catch (XMLStreamException e) {
			e.printStackTrace();
		}
		
	}
	
	//Returns the proecessed updates
	public Update process(){
		String name = update.getUser().getUserName();
		String[] nameArray = name.split("@");
		update.getUser().setUserName(nameArray[0]) ;
		System.out.println(update.getUser().getUserName());
		
		java.util.Date javaDate = new java.util.Date();
	    long javaTime = javaDate.getTime();
	    java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(javaTime);	
	    System.out.println(sqlTimestamp);
	    update.setUpdateTime(sqlTimestamp);
	    
		DMMLParser parser = new DMMLParser();
		try {
			update = parser.parseXMLData(update);
			System.out.println("Site: " + update.getService().toString());
			System.out.println("Data: " + update.getData());
		} catch (XMLStreamException e) {
			e.printStackTrace();
		}
		return update;
	}
	
	//Returns the tiy URL for URLS
	public String getTinyUrl(String fullUrl) throws HttpException, IOException {
		String tinyUrl = TinyURLUtils.getTinyUrl(fullUrl);
		return tinyUrl;
	}
	
}
